package com.heatup.apt.common.util;

import java.text.NumberFormat;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @see 优惠券工具类
 * @author Earvin
 *
 */
public class CouponUtil {
	private final static Logger logger = LoggerFactory.getLogger(CouponUtil.class);
	private final static ReentrantLock lock = new ReentrantLock();

	/**
	 * 私有构造函数
	 */
	private CouponUtil() {

	}

	/**
	 * @see 优惠券兑换码生产
	 * @param coupon_id 优惠券批次信息
	 * @return coupon_code 优惠券兑换码
	 */
	public static String generatorCoupinCode(final Integer coupon_id) {
		lock.lock();
		try {
			NumberFormat nf = NumberFormat.getInstance();
			nf.setGroupingUsed(false);
	    	nf.setMinimumIntegerDigits(4);
	    	nf.setMaximumIntegerDigits(4);
	    	String couponIdStr = nf.format(coupon_id);
			return couponIdStr+createId();
		} catch (Exception ex) {
			return null;
		} finally {
			lock.unlock();
		}
	}

	
	private static String createId()
    {
        String id = UUID.randomUUID().toString();
         
        id = DEKHash(id) + "";
         
        int diff = 12 - id.length();
        String randStr = RandomStringUtils.randomAlphabetic(12);
        for (int i = 0; i < diff; i++)
        {
            int randIndex = (int) (Math.random() * randStr.length());
            int index = (int) (Math.random() * id.length());
            id = id.substring(0, index) + randStr.charAt(randIndex) + id.substring(index, id.length());
        }
        return id;
    }
     
    private static int DEKHash(String str)
    {
        int hash = str.length();
 
        for (int i = 0; i < str.length(); i++)
        {
            hash = ((hash << 5) ^ (hash >> 27)) ^ str.charAt(i);
        }
 
        return (hash & 0x7FFFFFFF);
    }
    
    public  static void main(String args[]){
    	NumberFormat nf = NumberFormat.getInstance();
    	nf.setGroupingUsed(false);
    	nf.setMinimumIntegerDigits(4);
    	nf.setMaximumIntegerDigits(4);
    	//nf.format(101);
    	
    	System.out.println(generatorCoupinCode(10));
    }
}
